<!-- 轮播项组 -->
<template>
  <transition :name="animName">
    <!-- 如果轮播图显示的组件位置跟当前组件在视图中渲染的位置一样时才显示这个组件 -->
    <div class="carousel-item" v-if="currentIndex === selfIndex">
      <slot></slot>
    </div>
  </transition>
</template>

<script>
//这个标签是为了解决v3中给组件添加name属性
export default {
  name: "carouselItem",
};
</script>

<script setup>
import { getCurrentInstance } from "vue";

//获取当前实例
let instance = getCurrentInstance();

//通过getCurrentInstance获取当前子组件的所在位置的索引
let selfIndex = getCurrentInstance().vnode.key;

//获取父元素当前显示的子组件的索引值
let currentIndex = ref(instance.parent.ctx.currentIndex);

//执行动画的值
let animName = ref("animRight");

//监听父组件中轮播图当前显示的索引值和轮播图切换的方向
watch(
  [
    () => {
      return instance.parent.ctx.currentIndex;
    },
    () => {
      return instance.parent.ctx.scrollDirection;
    },
  ],
  (newValue, oldValue) => {
    currentIndex.value = newValue[0];
    newValue[1] === "next"
      ? (animName.value = "animRight")
      : (animName.value = "animLeft");
  }
);
</script>

<style lang="scss" scoped>
.carousel-item {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
}

img {
  width: 100%;
  height: 100%;
}

//实现动画,主要是使用vue3的transition动画
.animRight-enter-active,
.animRight-leave-active,
.animLeft-enter-active,
.animLeft-leave-active {
  //出去和进来 之前
  transition: all 0.3s linear;
}

.animRight-enter-from {
  //进入的开始位置
  transform: translateX(100%);
}

.animLeft-enter-from {
  transform: translateX(-100%);
}

.animRight-enter-to,
.animLeft-enter-to {
  //进入的结束位置
  transform: translateX(0);
}

.animRight-leave-from,
.animLeft-leave-from {
  //离开的开始位置
  transform: translateX(0);
}
.animRight-leave-to {
  //离开的结束位置
  transform: translateX(-100%);
}

.animLeft-leave-to {
  transform: translateX(100%);
}
</style>
